export function randomDirection(): number {
	return Math.random() > 0.5 ? 1 : -1;
}

export function randomSection(from: number, to: number): number {
	return Math.random() * (to - from) + from;
}

export function randomItem(items: Array<any>): any {
	if (!items) return null;

	const index = Math.round(this.randomSection(1, items.length));
	return items[index - 1];
}

export function checkProbability(rate: number, weight: number): boolean {
	const rand = Math.random() * weight;
	return rand <= rate;
}

/**
 * 角度转弧度
 */
export const deg2Rad: number = Math.PI / 180;

/**
 * 弧度转角度
 */
export const rad2Deg: number = 180 / Math.PI;

/**
 * 获得随机方向
 */
export function sign(x: number) {
	if (x > 0) {
		return 1;
	}
	if (x < 0) {
		return -1;
	}
	return 0;
}

/** 随时间变化进度值 */
export function progress(start: number, end: number, t: number) {
	return start + (end - start) * t;
}

/**
 * 插值
 * @param numStart
 * @param numEnd
 * @param t
 */
export function lerp(numStart: number, numEnd: number, t: number): number {
	let ratio = t;
	if (ratio > 1) {
		ratio = 1;
	} else if (t < 0) {
		ratio = 0;
	}

	return numStart * (1 - ratio) + numEnd * ratio;
}

/**
 *
 * @param angle1 角度插值
 * @param angle2
 * @param t
 */
export function lerpAngle(current: number, target: number, t: number): number {
	const currentAngle = current % 360;
	let targetAngle = target % 360;

	const dAngle: number = targetAngle - currentAngle;

	if (dAngle > 180) {
		targetAngle = currentAngle - (360 - dAngle);
	} else if (dAngle < -180) {
		targetAngle = currentAngle + (360 + dAngle);
	}

	return ((lerp(currentAngle, targetAngle, t) % 360) + 360) % 360;
}

/**
 * 按一定的速度从一个角度转向令一个角度
 * @param current
 * @param target
 * @param speed
 */
export function angleTowards(current: number, target: number, speed: number): number {
	const currentAngle = current % 360;
	let targetAngle = target % 360;

	const dAngle: number = targetAngle - currentAngle;

	if (dAngle > 180) {
		targetAngle = currentAngle - (360 - dAngle);
	} else if (dAngle < -180) {
		targetAngle = currentAngle + (360 + dAngle);
	}
	const dir = target - current;

	if (speed > Math.abs(dir)) {
		return targetAngle;
	}

	return (((currentAngle + speed * Math.sign(dir)) % 360) + 360) % 360;
}

export function clamp(value: number, minLimit: number, maxLimit: number) {
	if (value < minLimit) {
		return minLimit;
	}

	if (value > maxLimit) {
		return maxLimit;
	}

	return value;
}
